// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.require('axs.AuditRule');
goog.require('axs.AuditRules');
goog.require('axs.constants.Severity');
goog.require('axs.utils');

axs.AuditRule.specs.unfocusableElementsWithOnClick = {
    name: 'unfocusableElementsWithOnClick',
    severity: axs.constants.Severity.Warning,
    opt_requiresConsoleAPI: !(typeof $ === "function" && typeof $(document.body)._data === "undefined"),
    relevantNodesSelector: function(scope) {
        var potentialOnclickElements = scope.querySelectorAll('*');

        var unfocusableClickableElements = [];
        for (var i = 0; i < potentialOnclickElements.length; i++) {
            var eventListeners, element = potentialOnclickElements[i];
            if (element instanceof HTMLBodyElement)
                continue;
            if (axs.utils.isElementOrAncestorHidden(element))
                continue;
            if(typeof getEventListeners === "function") {
              eventListeners = getEventListeners(element); // This is not present in Firefox and likely causes the "requiresConsoleAPI" setting -- do we have any workarounds?
            } else if(typeof $ === "function" && typeof $(element)._data === "undefined") {
              eventListeners = $(element).data("events"); // Detects only jQuery event handlers pre-1.7
            }
            if (eventListeners && 'click' in eventListeners)
              unfocusableClickableElements.push(element);
        }
        return unfocusableClickableElements;
    },
    test: function(element) {
        return !element.hasAttribute('tabindex') &&
               !axs.utils.isElementImplicitlyFocusable(element);
    },
    code: 'AX_FOCUS_02'
};
